<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增付款单')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-payment-add">
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">付款单编号：</label>
                <div class="col-sm-8">
                    <input name="orderCode" class="form-control" type="text" th:value="${paymentOrderCode}" readonly required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">收款供应商：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="supplierId" name="supplierId" type="hidden" >
                        <input id="supplierName" name="supplierName" class="form-control" type="text" onclick="selectSupplier()" readonly required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">资金业务类型：</label>
                <div class="col-sm-8">
                    <select name="capitalType" class="form-control" th:with="type=${@dict.getType('capital_type')}">
                        <!--<option value="">请选择</option>-->
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">付款类型：</label>
                <div class="col-sm-8">
                    <select name="capitalSettlementWay" class="form-control" th:with="type=${@dict.getType('capital_settlement_way')}">
                        <!--<option value="">请选择</option>-->
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款银行：</label>
                <div class="col-sm-8">
                    <input id="receiveBank" name="receiveBank" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款账户：</label>
                <div class="col-sm-8">
                    <input id="receiveAccount" name="receiveAccount" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">付款日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="orderDate" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">付款金额：</label>
                <div class="col-sm-8">
                    <input id="payAmounts" name="payAmounts" class="form-control" type="number" step="0.01" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="200"></textarea>
                </div>
            </div>

            <h4 class="form-header h4">采购单列表数据</h4>
            <div class="row">
                <div class="col-sm-12">
                    <!--<button type="button" class="btn btn-white btn-sm" onclick="sub.addRow()"><i class="fa fa-plus"> 增加</i></button>-->
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>

        <div class="row">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <script th:inline="javascript">
        var prefix = ctx + "bill/payment"
        $("#form-payment-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.saveTab(prefix + "/add", $('#form-payment-add').serialize());
            }
        }

        $("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true,
            initialDate: new Date()
        });

        /* 选择供应商 */
        var supplierPrefix = ctx + "basic/supplier"
        function selectSupplier() {
            var url = supplierPrefix + '/selectSupplier';
            var options = {
                title: '选择供应商',
                url: url,
                callBack: doSubmitSupplier
            };
            $.modal.openOptions(options);
        }
        function doSubmitSupplier(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            var supplierId = rows.join();
            $('#supplierId').val(supplierId)
            var supplierName=iframeWin.selectColumns("supplierName").join();
            $('#supplierName').val(supplierName)
            var receiveBank=iframeWin.selectColumns("bank").join();
            $('#receiveBank').val(receiveBank)
            var receiveAccount=iframeWin.selectColumns("account").join();
            $('#receiveAccount').val(receiveAccount)


            //重置子表
            sub.removeAllRow();
            //根据供应商获取子表数据
            getPurchOrderList(supplierId)

            $.modal.close(index);
        }

        //初始化
        $(function() {
            init();
        });

        //获取子表数据
        function getPurchOrderList(supplierId){
            var data = {"supplierId":supplierId};
            var config = {
                url: prefix + "/item/selectPurchOrderAjaxList",
                type: "post",
                dataType: "json",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $.each(result.data,function(index,value){
                            var row = {
                                id: "",
                                purchId: value.purchId,
                                purchCode: value.purchCode,
                                noPayAmount: value.noPayAmount,
                                payAmount: 0,
                                remark:""
                            }
                            sub.addRow(row);
                        });
                    }else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();
                }
            };
            $.ajax(config)
        }

        function init() {
            var options = {
                data:[],
                //url: prefix + "/item/selectPurchOrderList",
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                // queryParams: {
                //     supplierId:supplierId
                // },
                //onLoadSuccess: onLoadSuccess,
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            return columnIndex + $.table.serialNumber(index);
                        }
                    },
                    {
                        field: 'id',
                        align: 'center',
                        title: 'id',
                        visible: false
                    },
                    {
                        field: 'purchCode',
                        align: 'center',
                        title: '采购单号',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].purchCode' value='%s' readonly>", index, value);
                            var purchId = $.common.sprintf("<input type='hidden' name='items[%s].purchId' value='%s'>", index, row.purchId);//采购单id 隐藏域

                            return html+purchId;
                        },
                    },
                    {
                        field: 'noPayAmount',
                        align: 'center',
                        title: '应付金额',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" name="items['+index+'].noPayAmount" value="'+value+'" maxlength="10" readonly>';
                            return html;
                        },
                    },
                    {
                        field: 'payAmount',
                        align: 'center',
                        title: '本次付款',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" step="0.01" name="items['+index+'].payAmount" value="'+value+'" maxlength="10" onchange="reloadRowPayAmountData('+index+','+row.noPayAmount+',this)" required>';
                            return html;
                        },
                    },
                    {
                        field: 'remark',
                        align: 'center',
                        title: '备注',
                        formatter: function(value, row, index) {
                            var html = '<textarea class="form-control"  name="items['+index+'].remark" maxlength="200">'+value+'</textarea>';
                            return html;
                        }
                    }
                ]
            };
            $.table.init(options);
        }

        /**
         * 修改计算金额
         * */
        function reloadRowPayAmountData(index,noPayAmount, obj) {
            console.info("==========================");
            if ($.common.isNotEmpty(index)) {
                var payAmount = $(obj).val();
                var regu = /^\d+(\.{0,1}\d{1,2})?$/;//非负浮点数（正浮点数 + 0）
                if ($.common.isEmpty(payAmount) || !regu.test(payAmount)) {
                    $.modal.alertWarning("不能为空或输入的不是非负浮点数(只能保留2位)");
                    return;
                }
                //判断金额不能大于应付金额
                if(parseFloat(noPayAmount)<parseFloat(payAmount)){
                    $.modal.alertWarning("付款金额不能大于应付金额");
                    return;
                }
                //更新字段数据
                updateCell(index,payAmount);
            }
        }

        //更新指定的列数据
        function updateCell(index, payAmount) {//更新表格数据
            var _data = new Object();//某行数据
            _data.payAmount = payAmount;
            $("#" + table.options.id).bootstrapTable("updateRow", {index: index, row: _data});
            //总计
            calculate()
        }


        /**
         * 计算合计商品各项值之和
         */
        function calculate() {
            var data = $("#" + table.options.id).bootstrapTable('getData');//查询表格所有数据
            console.info(JSON.stringify(data));
            var totalAmount = 0;
            $.each(data, function (index, obj) {
                if($.common.isNotEmpty(obj.payAmount)) {
                    totalAmount = numAdd(totalAmount, obj.payAmount);
                }
            });
            $('#payAmounts').val(totalAmount);
        }


    </script>
</body>
</html>